package com.xhtt.smart.card.common.util;

import com.xhtt.smart.card.common.error.SmartCardException;
import io.netty.util.internal.StringUtil;

/**
 * @author wangze
 * @date 2018-07-04 10:00.
 **/
public class HexConver {

    private static final String ZERO = "0";


    /**
     * 将最大值为255的short值，转换为byte
     *
     * @param intValue
     * @return
     */
    public static byte int8ToByte(int intValue) {

        return (byte) (intValue & 0xFF);
    }


    /**
     * byte转换为int
     *
     * @param byteSource
     * @return
     */
    public static int byteToInt(byte byteSource) {
        return byteSource & 0xFF;
    }

    /**
     * byte 转换为二进制,不足8位数，补足8位
     *
     * @param byteSource
     * @return
     */
    public static String byteToBin(byte byteSource) {
        String bin = Integer.toBinaryString(byteToInt(byteSource));
        int zeroLength = 8 - bin.length();
        for (int i = 0; i < zeroLength; i++) {
            bin = ZERO + bin;
        }
        return bin;
    }

    /**
     * 二进制 转换为byte string 最多只能是8位，并且都是0,1,最大255
     *
     * @param bin
     * @return
     */
    public static byte binToByte(String bin) {
        if (StringUtil.isNullOrEmpty(bin)) {
            throw new SmartCardException("bin为空");
        }
        short a = Short.parseShort(bin, 2);

        return (byte) (a & 0xFF);
    }

    /**
     * 将byte 转换 字符串，编码格式是ascii编码
     *
     * @param bytes
     * @return
     */
    public static String byteToAsciiString(byte[] bytes) {
        String result = "";
        if (bytes != null && bytes.length > 0) {
            for (byte b : bytes) {
                result += (char) (byteToInt(b));
            }
        }
        return result;
    }


    public static byte[] asciiStringToByte(String str) {
        if (StringUtil.isNullOrEmpty(str)) {
            throw new SmartCardException("参数为空");
        }
        byte[] bytes = new byte[str.length()];
        for (int i = 0; i < str.length(); i++) {

            bytes[i] = int8ToByte((int) str.charAt(i));
        }
        return bytes;

    }


    public static void main(String[] args) {

        System.out.println(int8ToByte(255));

        System.out.println(byteToBin((byte) 33));


        System.out.println(asciiStringToByte("123ASDFGBQ123456").length);
    }

}
